package com.xuecheng.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.api.teaching.model.dto.CourseWorkRecDTO;
import com.xuecheng.common.domain.page.PageRequestParams;
import com.xuecheng.common.domain.page.PageVO;
import com.xuecheng.common.util.StringUtil;
import com.xuecheng.teaching.convert.CourseWorkConvert;
import com.xuecheng.teaching.entity.CourseWorkRec;
import com.xuecheng.teaching.mapper.CourseWorkRecMapper;
import com.xuecheng.teaching.service.CourseWorkRecService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class CourseWorkRecServiceImpl extends ServiceImpl<CourseWorkRecMapper, CourseWorkRec> implements CourseWorkRecService {


    @Override
    public PageVO<CourseWorkRecDTO> queryWorkToPreview(PageRequestParams pageRequestParams, String courseName, Long companyId) {

        // 1.业务传入参数的判断
        if (ObjectUtils.isEmpty(pageRequestParams)) {
            pageRequestParams = new PageRequestParams();
        }
        Long pageNo = pageRequestParams.getPageNo();
        Integer pageSize = pageRequestParams.getPageSize();

        // 2.构建分页查询
        if (ObjectUtils.isEmpty(pageNo) || pageNo < 1) {
            pageNo = PageRequestParams.DEFAULT_PAGE_NUM;
        }

        if (ObjectUtils.isEmpty(pageSize) || pageSize < 1) {
            pageSize = PageRequestParams.DEFAULT_PAGE_SIZE;
        }

        Page<CourseWorkRec> page = new Page<>(pageNo, pageSize);

        // 3.构建条件查询
        LambdaQueryWrapper<CourseWorkRec> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtil.isNotBlank(courseName), CourseWorkRec::getCourseName, courseName);
        queryWrapper.eq(!(ObjectUtils.isEmpty(companyId)), CourseWorkRec::getCompanyId, companyId);
        // 4.查询
        Page<CourseWorkRec> pageResult = this.page(page, queryWrapper);
        List<CourseWorkRec> records = pageResult.getRecords();


        // 5.封装PageVo
        List<CourseWorkRecDTO> courseWorkRecDTOS = Collections.emptyList();
        if (!ObjectUtils.isEmpty(records)) {
            //使用mapStruct转换对象
            courseWorkRecDTOS = CourseWorkConvert.INSTANCE.entitys2dtos(records);
        }
        return new PageVO<>(courseWorkRecDTOS, page.getTotal(), pageNo, pageSize);

    }
}
